package com.susallwave.srcb.serviceimpl.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.susallwave.srcb.entity.sys.Role;
import com.susallwave.srcb.mapper.sys.RoleMapper;
import com.susallwave.srcb.response.Result;
import com.susallwave.srcb.response.ResultEnum;
import com.susallwave.srcb.service.sys.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author MyBatisPlusGenerator
 * @since 2025-07-19
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Override
    public Result<Page<Role>> page(int pageNum, int pageSize, String code, String name, String status) {
        Page<Role> page = new Page<>(pageNum,pageNum);
        LambdaQueryWrapper<Role> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(code)) {
            qw.eq(Role::getRoleCode,code);
        }
        if (StringUtils.isNotBlank(name)) {
            qw.eq(Role::getRoleName,name);
        }
        if (StringUtils.isNotBlank(status)) {
            qw.eq(Role::getRoleStatus,status);
        }
        return Result.success( this.page(page,qw));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> add(Role role) {
        String code = role.getRoleCode();
        String name = role.getRoleName();
        int codeInt = this.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, code));
        int nameInt = this.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, name));

        if (codeInt>0) {
            return Result.error(ResultEnum.REPEAT_CODE);
        }
        if (nameInt>0) {
            return Result.error(ResultEnum.REPEAT_NAME);
        }
        this.save(role);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> edit(Role role) {
        if (role.getId()==null) {
            return Result.error(ResultEnum.ID_NULL);
        }
        String code = role.getRoleCode();
        String name = role.getRoleName();
        int codeInt = this.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleCode, code));
        int nameInt = this.count(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, name));

        if (codeInt>0) {
            return Result.error(ResultEnum.REPEAT_CODE);
        }
        if (nameInt>0) {
            return Result.error(ResultEnum.REPEAT_NAME);
        }
        this.updateById(role);
        return Result.success();
    }
}
